﻿using System;
using System.Net;
using System.Threading;
using Platformer_Example.Controller.Network;
using Platformer_Example.Controller.Network.Messages;
using Transformable_Engine_v2.Engine;

namespace Platformer_Example.Screen.QuickGame
{
    public partial class QuickGame
    {
        private NetworkClient _client;
        private ClientData _clientData;

        private void StartClient(string playerName)
        {
            _client = new NetworkClient();
            _clientData = new ClientData();
            _client.OnSearchGameResponse += OnClientSearchGameResponse;
            _client.OnJoinGameDeclineResponse += OnClientJoinGameDeclineResponse;
            _client.OnJoinGameAcceptResponse += OnClientJoinGameAcceptResponse;
            _client.OnLoadGame += OnClientLoadGame;

            _clientData.RefreshServers();
            _client.SearchGames();
            Thread.Sleep(500);
            Console.WriteLine("Select a server to join");
            Console.Write(">> ");
            /*
            int serverId = Convert.ToInt32(Console.ReadLine());
            /*/
            const int serverId = 0;
            Console.WriteLine(serverId);
            //*/
            _clientData.SelectServer(serverId);
            _client.TryJoiningServer(_clientData.ServerIPAddress, playerName);
        }

        private void OnClientLoadGame(Controller.Network.Messages.LoadGame message, IPAddress senderaddress)
        {
            ClientStartGame(message);
        }

        private void ClientStartGame(Controller.Network.Messages.LoadGame gameData)
        {
            _client.OnSearchGameResponse -= OnClientSearchGameResponse;
            _client.OnJoinGameDeclineResponse -= OnClientJoinGameDeclineResponse;
            _client.OnJoinGameAcceptResponse -= OnClientJoinGameAcceptResponse;
            _client.OnLoadGame -= OnClientLoadGame;

            ChangeScreen(new LoadGame.LoadGame(_client, _clientData, gameData));
        }

        private void OnClientJoinGameAcceptResponse(JoinGameAcceptResponse message, IPAddress senderaddress)
        {
            Console.WriteLine(message);
            _clientData.SetNetworkId(message.NetworkId);
        }

        private void OnClientJoinGameDeclineResponse(JoinGameDeclineResponse message, IPAddress senderaddress)
        {
            Console.WriteLine("The server has declined the request to join the game");
            Console.ReadLine();
            Game.Close();
        }

        private void OnClientSearchGameResponse(SearchGameResponse message, IPAddress senderAddress)
        {
            _clientData.AddServer(senderAddress, message);
        }
    }
}